// pages/formTempPass/formTempPass.js
import api from '../../utils/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    applyName: '',
    workno: '',
    branch: "",
    phone: "",
    visitorTypeHide: true,
    visitorType: "请选择",
    pertype: 1,
    company: "",
    organizerType: 1,
    visitRsn: "",
    currDate: "", // 当前日期
    startdate: "",
    enddate: "",
    minDate: "",
    maxDate: "",
    nextApprover: "",
    showDialog: false,

    visitorTypeList: [{
        lable: "总分行人员",
        value: 0
      },
      {
        lable: "外员",
        value: 1
      },
      {
        lable: "其他",
        value: 2
      }
    ],
    visitorsList: [],
    showBtnArea: false,
    requestId: -1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserInfo()
    this.getCurrDate()
    this.setDateRange(new Date(),14)

    if (options.id != null) {
      this.setData({
        requestId: options.id,
      })
      this.getRequestDetail()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //点击放大图片
  previewPic: function (e) {
    let imgUrls = [e.currentTarget.dataset.url]
    wx.previewImage({
      urls: imgUrls, //需要预览的图片http链接列表，注意是数组
      current: '', // 当前显示图片的http链接，默认是第一个
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },

  // 显示遮罩层
  showModal: function (e) {
    let popup = e.currentTarget.dataset.index
    var that = this;

    that.setData({
      visitorTypeHide: popup == "visitor" ? false : true,
    })
    var animation = wx.createAnimation({
      duration: 600, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn(); //调用显示动画
    }, 200)
  },

  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 500, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown(); //调用隐藏动画   
    setTimeout(function () {
      that.setData({
        visitorTypeHide: true,
      })
    }, 500) //先执行下滑动画，再隐藏模块
  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(700).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },

  // 人员类型变换
  visitorTypeChange: function (e) {
    this.setData({
      visitorType: e.detail.value,
    })
    this.hideModal()
  },

  datePickerChange: function (e) {
    let type = e.currentTarget.dataset.type

    if (type == "start") {
      const selectedStartDay = e.detail.value;
      this.setData({
        startdate: selectedStartDay
      })
      this.setDateRange(selectedStartDay,14)
    } else if (type == "end") {
      this.setData({
        enddate: e.detail.value
      });
    } else {
      let index = e.currentTarget.dataset.index
      let tempList = this.data.visitorsList

      tempList[index].arrivedate = e.detail.value
      this.setData({
        visitorsList: tempList
      })
    }
  },

  regionPickerChange: function (e) {
    let index = e.currentTarget.dataset.index
    let tempList = this.data.visitorsList

    tempList[index].visitOrigAdd = e.detail.value.join("")
    this.setData({
      visitorsList: tempList
    })
  },

  radioChange: function (e) {
    let type = e.currentTarget.dataset.type
    if (type == 'place') {
      this.setData({
        organizerType: e.detail.value == "1" ? 1 : (e.detail.value == "2" ? 2 : 3)
      })
    } else {
      let index = e.currentTarget.dataset.index
      let tempList = this.data.visitorsList

      switch (type) {
        case "fever":
          tempList[index].feverCond = e.detail.value == "true" ? true : false
          break;
        case "danger":
          tempList[index].riskArrive = e.detail.value == "true" ? true : false
          break;
      }
      this.setData({
        visitorsList: tempList
      })
    }
  },

  addVisitor: function () {
    let tempList = this.data.visitorsList
    let visitor = {
      visitName: "",
      visitOrigAdd: "请选择",
      arrivedate: this.data.startdate,
      feverCond: null,
      riskArrive: null,
      jobDescription: "",
    }

    tempList.push(visitor)
    this.setData({
      visitorsList: tempList,
      showBtnArea: true
    })
  },

  deleteVisitor: function (e) {
    let index = e.currentTarget.dataset.index

    let tempList = this.data.visitorsList
    tempList.splice(index, 1)
    if (tempList.length == 0) {
      this.setData({
        showBtnArea: false,
      })
    }
    this.setData({
      visitorsList: tempList,
    })
  },

  inputChange: function (e) {
    let type = e.currentTarget.dataset.type
    let index = e.currentTarget.dataset.index
    let tempList = this.data.visitorsList

    if (type == "company") {
      this.setData({
        company: e.detail.value
      })
    } else if (type == "reason") {
      this.setData({
        visitRsn: e.detail.value
      })
    } else {
      tempList[index].visitName = e.detail.value
      this.setData({
        visitorsList: tempList
      })
    }
  },

  uploadImage: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index
    let tempList = this.data.visitorsList

    wx.chooseImage({
      //限定上传张数x
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        //显示等待框
        wx.showLoading({
          title: '图片上传中',
          mask: true
        })
        //调取图片上传
        wx.uploadFile({
          //对象转字符串.join("")
          filePath: res.tempFilePaths.join(""),
          name: 'img',
          url: api.uploadImg,
          success: function (res) {
            wx.hideLoading()
            if (res.data.toString().includes("Too Large")) {
              wx.showToast({
                title: '图片超过1M',
                icon: 'error'
              })
            } else {
              var data = JSON.parse(res.data)
              if (data.data != null) {
                tempList[index].jobDescription = data.data.imgUrl
                that.setData({
                  visitorsList: tempList
                })
              }
              if (data.state == "1") {
                wx.showToast({
                  title: '图片上传成功',
                })
              } else if (data.state == "2") {
                wx.showToast({
                  title: '图片上传失败，请重新上传或选择分辨率较小的图片',
                  icon: 'error'
                })
              }
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '图片上传失败，请重新上传或选择分辨率较小的图片',
              icon: 'error'
            })
          },
          complete: () => {
            // console.log("complete")
          }
        })
      },
    })
  },

  // 获取当前日期
  getCurrDate: function () {
    let today = new Date()
    let temp = this.formatDate(today)
    this.setData({
      currDate: temp,
      startdate: temp,
      enddate: temp,
      arrivedate: temp,
    })
  },

  setDateRange:function(selectedDay,days){
        if(selectedDay) {
          const startDateObj=new Date(selectedDay);
          const minDate = this.formatDate(startDateObj);
          const maxDate = this.formatDate(this.addDays(startDateObj,days));
          console.log(minDate+":"+maxDate)
          this.setData({
            minDate: minDate,
            maxDate: maxDate,
          });
        }
        else
        {
          this.setData({
                  minDate:'',
                  maxDate:'',
                });
        }
        
  },

  // 辅助函数：格式化日期为 YYYY-MM-DD
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      },
    
      // 辅助函数：增加天数
      addDays(date, days) {
        const result = new Date(date);
        result.setDate(result.getDate() + days);
        return result;
      },

  // 日期格式调整
  dateFormat: function (time) {
    return time < 10 ? "0" + time : time
  },

  // 人员类别文字与值转换
  getPeopleType: function (getText, value) {
    let tempList = ["", "总分行人员", "外员", "其他"]
    if (getText) {
      return tempList[value]
    } else {
      for (let i in tempList) {
        if (tempList[i] == value) {
          return i
        }
      }
    }
  },
  

  validate: function () {
    let data = this.data
    if (data.visitorType == "请选择") {
      return "请选择人员类型"
    }
    if (data.company == "") {
      return "所属单位不能为空"
    }
    if (data.visitRsn == "") {
      return "来访理由不能为空"
    }
    
    if(data.startdate=='')
    {
      return "来访开始日期不能为空"
    }

    if(data.enddate=='')
    {
      return "来访结束日期不能为空"
    }

    if(data.enddate<data.startdate)
    {
      return "来访结束日期不能早于开始日期"
    }

    if(data.enddate>data.maxDate)
    {
      return "来访结束日期不能超过开始日期两周"
    }

    for (let visitor in data.visitorsList) {
      if (data.visitorsList[visitor].visitName == "") {
        return "来访者姓名不能为空"
      }
      if (data.visitorsList[visitor].arrivedate > data.enddate||data.visitorsList[visitor].arrivedate < data.startdate) {
        return "到本地时间为来访开始和结束日期之间"
      }

      // if (data.visitorsList[visitor].visitOrigAdd == "请选择") {
      //   return "请选择来访者从何处来"
      // }
      // if (data.visitorsList[visitor].feverCond == null) {
      //   return "请选择来访者身体是否不适"
      // }
      // if (data.visitorsList[visitor].riskArrive == null) {
      //   return "请选择来访者14天内是否去中高风险区"
      // }
      // if (data.visitorsList[visitor].jobDescription == "") {
      //   return "请上传工作说明"
      // }
    }
    return "finished"
  },

  sendRequest: function (e) {
    // 0-保存 1-提交
    let url = e == 1 ? api.formSubmitRequest : api.formSaveRequest
    let _this = this

    //显示等待框
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    wx.request({
      url: url,
      method: "POST",
      data: {
        id: _this.data.requestId,
        applyName: _this.data.applyName,
        workno: _this.data.workno,
        branch: wx.getStorageSync("logindata").data.department,
        phone: _this.data.phone,
        applyType: 2,
        pertype: _this.getPeopleType(false, _this.data.visitorType),
        company: _this.data.company,
        organizerType: _this.data.organizerType,
        visitRsn: _this.data.visitRsn,
        startdate: _this.data.startdate,
        enddate: _this.data.enddate,
        visitorDetailList: _this.data.visitorsList,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading()
        if (res.data.state == 1) {
          let message = e == 1 ? "提交成功" : "保存成功"
          wx.showToast({
            icon: 'success',
            title: message,
          })
          _this.goBack()
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },

  goBack: function () {
    if (wx.getStorageSync('source')) {
      // console.log('公众号退回')
      wx.reLaunch({
        url: '/pages/formHome/formHome'
      })
      wx.removeStorageSync('source')
    } else {
      // console.log('正常流程退回')
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  getNextApprover: function () {
    let isFinished = this.validate()
    if (isFinished != "finished") {
      // wx.showToast({
      //   icon: 'error',
      //   title: isFinished,
      // })
      wx.showModal({
        content: isFinished,
        showCancel: false
      })
      return
    }
    let _this = this

    wx.request({
      url: api.formGetNextApprover,
      method: "GET",
      data: {
        workno: _this.data.workno,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.state == 1) {
          _this.setData({
            showDialog: true,
            nextApprover: res.data.data.name
          })
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },

  cancel: function (e) {
    let btnIndex = e.detail.index

    if (btnIndex == 0) {
      // 取消
      this.setData({
        showDialog: false
      })
    } else {
      // 确认
      this.sendRequest(1)
    }
  },

  getUserInfo: function () {
    let _this = this
    wx.request({
      url: api.getUserInfo + '?workno=' + wx.getStorageSync("workNo"),
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          _this.setData({
            applyName: res.data.data[0].name,
            workno: res.data.data[0].workno,
            branch: res.data.data[0].depName,
            phone: res.data.data[0].mobile,
          })
        }
      }
    })
  },

  getRequestDetail: function (e) {
    let that = this

    wx.request({
      url: api.formRequestDetail + this.data.requestId,
      method: "GET",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.state == 1) {
          that.setData({
            visitorType: that.getPeopleType(true, res.data.data.pertype),
            company: res.data.data.company,
            organizerType: res.data.data.organizerType,
            visitRsn: res.data.data.visitRsn,
            pertype: res.data.data.pertype,
            visitorsList: res.data.data.visitorDetailList,
            startdate: res.data.data.startdate,
            enddate: res.data.data.enddate,
            showBtnArea: true
          })
        }
      }
    })
  },
})